package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TableRow;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.GTCheckListAdapter;
import com.example.administrator.yanfoxconn.adapter.LCMainUpCheckAdapter;
import com.example.administrator.yanfoxconn.bean.GTMain;
import com.example.administrator.yanfoxconn.bean.LCMessage;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.ChangeTextUtils;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description 營建 現場勘查記錄 列表
 * @Author song
 * @Date 2021/12/21 10:20
 */
public class LCGetListActivity extends BaseActivity implements View.OnClickListener {
    private final int MESSAGE_SET_TEXT = 1;//掃描成功賦值
    private final int MESSAGE_TOAST = 2;//掃描失敗彈出框
    private final int MESSAGE_UP = 3;//提交信息回復
    private final int MESSAGE_SHOW = 4;//顯示提醒
    private final int MESSAGE_NETMISTAKE = 5;//網絡錯誤
    private final int MESSAGE_SET_DIRECTOR = 6;//教師賦值
    private final int MESSAGE_SENF_TOAST = 7;//區域賦值
    private final int MESSAGE_SET_FLOOR = 8;//问卷賦值

    private List<LCMessage> lcMessages,dMessage;//項目信息,簽核主管
    private List<String> namelist,codelist;
    private GTCheckListAdapter gtCheckListAdapter;//列表適配器
    private String dName,dCode;
    private int mWitch=0;
    private String type="";    //類別
    private String url="";    //獲取點檢進度

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.tv_three)
    TextView tvThree;//承揠人

    @BindView(R.id.et_danwei)
    EditText etDanWei;//承辦人

    @BindView(R.id.tr_one)
    TableRow trOne;
    @BindView(R.id.tr_two)
    TableRow trTwo;
    @BindView(R.id.tr_four)
    TableRow trFour;

    @BindView(R.id.btn_lc_search)
    Button btnLcSearch;//查詢
    @BindView(R.id.btn_today)
    Button btnUnDo;//待維護
    @BindView(R.id.btn_undo)
    Button btnDone;//已維護
    @BindView(R.id.lv_process)
    ListView lvProcess;//進度列表

    private String flag="N";//左：待維護N ，右：已維護Y
    private String result;//网络获取结果
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gt_check);
        ButterKnife.bind(this);

        tvTitle.setText("現場勘查");
        tvThree.setText("承辦人");
        btnBack.setOnClickListener(this);
        btnLcSearch.setOnClickListener(this);
        btnLcSearch.setVisibility(View.VISIBLE);
        btnDone.setOnClickListener(this);
        btnDone.setText("已維護");//Y
        btnUnDo.setText("待維護");//N
        btnUnDo.setOnClickListener(this);
        trOne.setVisibility(View.GONE);
        trTwo.setVisibility(View.GONE);
        trFour.setVisibility(View.GONE);

        etDanWei.setText(FoxContext.getInstance().getName());
        getMessage(FoxContext.getInstance().getName(),flag);

        lvProcess.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (flag.equals("Y")){
                    if (lcMessages.get(position).getSign_flag().equals("已退件")||lcMessages.get(position).getSign_flag().equals("")){
                        ToastUtils.showLong(LCGetListActivity.this,"長按查看");
                       }else{
                        ToastUtils.showLong(LCGetListActivity.this,"此狀態無操作！");
                   }
                }else{
                    Intent intent0 = new Intent(LCGetListActivity.this,LCMainUpActivity.class);
//                    intent0.putExtra("result",lcMessages.get(i).getProject_no());
                    intent0.putExtra("gcc01",lcMessages.get(i).getGcc01());
                    intent0.putExtra("flag","N");
//                    intent0.putExtra("message",lcMessages.get(i));
                    startActivity(intent0);
                }
            }
        });

        lvProcess.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                position = i;
                if (lcMessages.get(position).getSign_flag().equals("已退件")||lcMessages.get(position).getSign_flag().equals("")){
                    itemOnLongClick();  }else{
               ToastUtils.showLong(LCGetListActivity.this,"此狀態無操作！");}
                return false;
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_lc_search:
                Log.e("------","00000000");
                getMessage(etDanWei.getText().toString(),flag);
                break;
            case R.id.btn_today:
                btnDone.setBackgroundColor(getResources().getColor(R.color.color_cccccc));
                btnUnDo.setBackgroundColor(getResources().getColor(R.color.color_7edbf4));
                flag="N";
                getMessage(etDanWei.getText().toString(),flag);
                break;
            case R.id.btn_undo:
                btnDone.setBackgroundColor(getResources().getColor(R.color.color_7edbf4));
                btnUnDo.setBackgroundColor(getResources().getColor(R.color.color_cccccc));
                flag="Y";
                getMessage(etDanWei.getText().toString(),flag);
                break;
        }

    }


    private void getMessage(String name,String flag) {
        try {

            String name1 = URLEncoder.encode(URLEncoder.encode(ChangeTextUtils.simToTra(name), "UTF-8"), "UTF-8");
//            String name2 = URLEncoder.encode(URLEncoder.encode(ChangeTextUtils.simToTra("白鳳圓"), "UTF-8"), "UTF-8");

            url = Constants.HTTP_LC_CONSTRUCT_ITEMS + "?name=" + name1 + "&flag=" + flag;

            Log.e("---------", "result==fff===" + url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }
        showDialog();

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);
                dismissDialog();

                if (result != null) {
                    Log.e("---------", "result==fff===" + result);

                    if (result != null) {
                        Gson gson = new Gson();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("code").getAsString();
                        lcMessages = new ArrayList<LCMessage>();
                        if (errCode.equals("200")) {
                            JsonArray array = jsonObject.get("data").getAsJsonArray();

                            for (JsonElement type : array) {
                                LCMessage humi = gson.fromJson(type, LCMessage.class);
                                lcMessages.add(humi);
                            }
                            Message message = new Message();
                            message.what = MESSAGE_SET_TEXT;
//                            message.obj = jsonObject.get("errMessage").getAsString();

                            mHandler.sendMessage(message);

                        } else {
                            Log.e("-----------", "result==" + result);
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("msg").getAsString();
                            mHandler.sendMessage(message);
                        }
                    } else {
                        Message message = new Message();
                        message.what = MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                }}
            }.start();
        }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_TOAST://Toast彈出
                    aboutAlert(msg.obj.toString(),MESSAGE_TOAST);
                    if (lcMessages!=null&&lcMessages.size()>0){
                        lcMessages.clear();
                    }
                    dismissDialog();
                    gtCheckListAdapter = new GTCheckListAdapter(LCGetListActivity.this,lcMessages,flag,"lc");
                    lvProcess.setAdapter(gtCheckListAdapter);
                    break;
                case MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(LCGetListActivity.this,R.string.net_mistake);
                    break;
                case MESSAGE_UP://提交響應
                    worningAlert(msg.obj.toString(),MESSAGE_UP);
                case MESSAGE_SET_TEXT://進度賦值
                    dismissDialog();
                    gtCheckListAdapter = new GTCheckListAdapter(LCGetListActivity.this,lcMessages,flag,"lc");
                    lvProcess.setAdapter(gtCheckListAdapter);
                    break;
                case MESSAGE_SHOW:
                    ToastUtils.showLong(LCGetListActivity.this,msg.obj.toString());
                    getMessage(etDanWei.getText().toString(),flag);
                    break;
                case MESSAGE_SET_DIRECTOR:
                    String[] name = new String[]{};
                    String[] code = new String[]{};
                    namelist=new ArrayList<>();
                    codelist=new ArrayList<>();
                    for (int i=0;i<dMessage.size();i++){
                        namelist.add(dMessage.get(i).getDir_name());
                        codelist.add(dMessage.get(i).getDir_code());
                    }
                    name=namelist.toArray(new String[namelist.size()]);
                    code=codelist.toArray(new String[codelist.size()]);
                    study4(name,code);
                    break;
                case MESSAGE_SENF_TOAST:
                    ToastUtils.showLong(LCGetListActivity.this,msg.obj.toString());
                    getMessage(etDanWei.getText().toString(),flag);
                    break;
            }
            super.handleMessage(msg);
        }
    };

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==MESSAGE_TOAST){
                            dismissDialog();
                        }

                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
    private void worningAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==MESSAGE_TOAST){

                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
int position;
    private void itemOnLongClick(){

        lvProcess.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
                if (flag.equals("Y")){
                contextMenu.add(0,0,0,"修改");
                    contextMenu.add(0,1,0,"取消");
                contextMenu.add(0,2,0,"發送");}
            }
        });
    }
    public boolean onContextItemSelected(MenuItem item){
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();


        switch (item.getItemId()){
            case 0://修改
                if (lcMessages.get(position).getSign_flag().equals("已退件")||lcMessages.get(position).getSign_flag().equals("")){
                Intent intent = new Intent(LCGetListActivity.this,LCMainUpActivity.class);
                intent.putExtra("flag","Y");
                intent.putExtra("gcc01",lcMessages.get(position).getGcc01());
//                intent.putExtra("scId",routeMessageList.get(position).getSc_id());
                startActivity(intent);}else{
    ToastUtils.showShort(LCGetListActivity.this,"此狀態不可修改！");
}
                break;
            case 1://取消
                getCancel(lcMessages.get(position).getGcc01());
                break;
            case 2://發送
                getDirector();
                break;
        }
        return super.onContextItemSelected(item);
    }

    //取消工程
    private void getCancel(String gcc01){
        showDialog();
        final String url = Constants.HTTP_LC_CONSTRUCT_CANCEL+"?gcc01="+gcc01 ;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);
                Log.e("---------", "==fff===" + url);
                dismissDialog();
                if (result != null) {
                    Gson gson = new Gson();
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {

                        Message message = new Message();
                        message.what = MESSAGE_SHOW;
                        message.obj = jsonObject.get("msg").getAsString();
                        mHandler.sendMessage(message);

                        Log.e("---------", "result==fff===" + result);
                    } else{
                        Message message = new Message();
                        message.what = MESSAGE_SHOW;
                        message.obj = jsonObject.get("msg").getAsString();
                        mHandler.sendMessage(message);
                    }
                }else{
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            } }.start();
    }


    //獲取發送主管
    private void getDirector(){
        showDialog();
        final String url = Constants.HTTP_LC_CONSTRUCT_DIRECTOR ;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);
                Log.e("---------", "==fff===" + url);
                dismissDialog();
                if (result != null) {
                    Gson gson = new Gson();
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {
                        dMessage = new ArrayList<LCMessage>();
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        for (JsonElement type : array) {
                            LCMessage humi = gson.fromJson(type, LCMessage.class);
                            dMessage.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_DIRECTOR;
                        message.obj = jsonObject.get("msg").getAsString();
                        mHandler.sendMessage(message);

                        Log.e("---------", "result==fff===" + result);
                    } else{
                        Message message = new Message();
                        message.what = MESSAGE_SHOW;
                        message.obj = jsonObject.get("msg").getAsString();
                        mHandler.sendMessage(message);
                    }
                }else{
                    Message message = new Message();
                    message.what = MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            } }.start();
    }
    //待單選，彈出框
    protected void study4(String[] dname,String[] dcode) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setSingleChoiceItems(
                        dname, 0,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Log.e("选择", "" + dname[which]+dcode[which]);
                                mWitch=which;
                                dName=dname[which];
                                dCode=dcode[which];
                            }
                        }).setNegativeButton("取消", null)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (mWitch==0){

                            setSend( dcode[0],dname[0]);
                        }else {
                            setSend(dCode, dName);
                        }
                    }
                }).show();
    }
    //發送
    private void setSend(String dCode,String dName) {
        showDialog();
        try {

            String name1 = URLEncoder.encode(URLEncoder.encode(ChangeTextUtils.simToTra(dName), "UTF-8"), "UTF-8");
            String name2 = URLEncoder.encode(URLEncoder.encode(ChangeTextUtils.simToTra(FoxContext.getInstance().getName()), "UTF-8"), "UTF-8");

            url = Constants.HTTP_LC_CONSTRUCT_SEND+"?gcc01="+lcMessages.get(position).getGcc01()+"&dir_code2="+dCode+"&dir_name2="+name1+"&sys_id="+FoxContext.getInstance().getLoginId()+"&sys_name="+name2; //此處寫上自己的URL
            Log.e("---------", "result==fff===" + url);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();

        }
        new Thread() {
            @Override
            public void run() {
                try {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);
                Log.e("---------", "==fff===" + url);
                dismissDialog();
//                    Message message = new Message();
//                    message.what = MESSAGE_SENF_TOAST;
//                    message.obj = "成功";
//                    mHandler.sendMessage(message);
                if (result != null) {
                        dismissDialog();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("code").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = MESSAGE_SENF_TOAST;
                            message.obj = jsonObject.get("msg").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("msg").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(LCGetListActivity.this);
                }
            }
        }.start();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        btnDone.setBackgroundColor(getResources().getColor(R.color.color_cccccc));
        btnUnDo.setBackgroundColor(getResources().getColor(R.color.color_7edbf4));
        flag="N";
        if (etDanWei.getText().toString().equals("")){

            getMessage(FoxContext.getInstance().getName(),flag);
        }else{
            getMessage(etDanWei.getText().toString(),flag);
        }
    }
}
